package com.google.code.alpaca.example.client;

import net.customware.gwt.dispatch.client.DefaultExceptionHandler;
import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.dispatch.client.standard.StandardDispatchAsync;

import com.google.code.alpaca.example.model.Message;
import com.google.code.alpaca.example.rpc.MessageSaveAction;
import com.google.code.alpaca.example.rpc.VoidResult;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

/**
 * 
 * @author drone
 * @version 1.0
 */
public class MessageForm extends HorizontalPanel {

  private final DispatchAsync dispatch = new StandardDispatchAsync(
      new DefaultExceptionHandler());

  private final TextBox textBox;
  private final Button button;
  private MessageBox messageBox;

  public MessageForm() {
    Label label = new Label("Text: ");
    label.setStyleName("textLabel");
    add(label);

    textBox = new TextBox();
    label.setStyleName("textBox");
    add(textBox);

    button = new Button("Create");
    button.addStyleName("sendButton");
    button.addClickHandler(new SayClickHandler());
    add(button);
  }

  public void setMessageBox(MessageBox messageBox) {
    this.messageBox = messageBox;
  }

  protected class SayClickHandler implements ClickHandler {

    @Override
    public void onClick(ClickEvent event) {
      Message message = new Message();
      message.setText(textBox.getText());

      AsyncCallback<VoidResult> callback = new AsyncCallback<VoidResult>() {

        @Override
        public void onFailure(Throwable caught) {
          messageBox.update();
        }

        @Override
        public void onSuccess(VoidResult result) {
          messageBox.update();
        }

      };
      
      dispatch.execute(new MessageSaveAction(message), callback);

      textBox.setText("");
    }
  }
}
